#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import logging
#logging.basicConfig(level=logging.INFO)
logging.basicConfig(filename='log', filemode="w", level=logging.INFO)
mylogger=logging.getLogger()
mylogger.addHandler(logging.StreamHandler())
import pdb
import sys
import  shutil 
import re

#regex expression:[\d]{2}-[\d]{2}\s+[\d]{2}:[\d]{2}:[\d]{2}.[0-9]+\s+[0-9]+\s+[0-9]+
#06-16 17:24:34.899 345566  4541

'筛选特定的字符串'
__author__='fengxw'

this_file_path_ = os.path.split(os.path.realpath(__file__))[0]
logging.info('this py file in this path:'+this_file_path_)

cmd_={}

def deal_cmd(_cmd):
    logging.info('cmd:'+str(_cmd))
    if _cmd.has_key('-l'):
        filter_single_line(_cmd['-l'])
    elif _cmd.has_key('-ml'):
        filter_multi_line(_cmd['-ml'])
    elif _cmd.has_key('-x'):
        filter_special(_cmd['-x'])
    elif _cmd.has_key('-split'):
        split_file(_cmd['-split'])
    else:
        logging.error('not define cmd')

def split_file(_split_str):
    logging.info('split :'+_split_str)
    pattern = re.compile(_split_str ,re.I)
    index = 0

    src_file_path = cmd_['-f']
    if False == os.path.exists(src_file_path):
        logging.error('file not exist:'+src_file_path)
        return -1

    src_file = open(src_file_path,'r')
    src_content = src_file.readlines()

    out_part_dir = 'out'
    if False == os.path.exists(out_part_dir):
        os.mkdir(out_part_dir)
    else:
        os.system('rm -rf '+out_part_dir+'/*')

    out_part_file = open(out_part_dir+'/'+'part_'+str(index) , 'w')
    for line in src_content:
        rst = re.search(pattern,line)
        if None!=rst:#match
            if None!=out_part_file:
                out_part_file.flush()
                out_part_file.close()
            logging.info('start write file:'+out_part_dir+'/'+'part_'+str(index))
            out_part_file = open(out_part_dir+'/'+'part_'+str(index) , 'w')
            index+=1
        out_part_file.write(line)

    modify_file_name(out_part_dir)
    os.system('ls -l '+out_part_dir)

def modify_file_name(_dir):
    logging.info('start modify all file name')
    cur_path = this_file_path_+'/'+_dir
    for root ,dirs ,files in os.walk(_dir ,topdown=False):
        for file_item in files:
            logging.info('modify file:'+file_item)
            new_file_name = get_file_name(cur_path , file_item)
            shutil.move(cur_path+'/'+file_item ,cur_path+'/'+new_file_name)
    pass

def get_file_name(_cur_path , _file_name):
    src_file = open(_cur_path+'/'+_file_name,'r')
    src_content = src_file.readlines()
    start_time = ''
    end_time = ''

    date_pattern = re.compile('[\d]{2}-[\d]{2}\s+[\d]{2}:[\d]{2}:[\d]{2}.[0-9]+',re.I)

    for line in src_content:
        rst =re.search(date_pattern , line)
        if None!=rst:#match
            start_time = rst.group()

    start_time = convert_to_window_can_see(start_time)

    i = len(src_content)-1
    while i>=0:
        rst =re.search(date_pattern , src_content[i])
        if None!=rst:#match
            end_time = rst.group()
            break
        i-=1

    end_time = convert_to_window_can_see(end_time)

    return _file_name+'___'+start_time+'+'+end_time
            
def convert_to_window_can_see(_str):
    _str = _str.replace(' ','_')
    _str = _str.replace('.','_')
    _str = _str.replace(':','_')
    return _str

def filter_special(_str):
    logging.info('filter_special enter')
    pattern = re.compile(_str ,re.I)

    src_file_path = cmd_['-f']
    if False == os.path.exists(src_file_path):
        logging.error('file not exist:'+src_file_path)
        return -1

    src_file = open(src_file_path,'r')
    src_content = src_file.readlines()

    dest_content = []

    line_index = 0;
    while line_index < len(src_content):
        line = src_content[line_index]
        rst =re.search(pattern , line)
        if None!=rst:
            #logging.info('==============:'+line)
            #pdb.set_trace()
            dest_content.append(line)
            no_date_line = find_no_date_line(line_index ,src_content)
            line_index = line_index + len(no_date_line)+1
            dest_content+=no_date_line
        else:
            #logging.info('--------------:'+line)
            line_index=line_index+1

    dest_file = open('./rst','w')
    dest_file.writelines(dest_content)

def find_no_date_line(_startI , _content):
    #logging.info('begin-->')
    #logging.info(_content[_startI])
    _startI+=1
    #logging.info(_content[_startI])
    no_date_line = []
    while _startI < len(_content):
        if False == is_exist_date(_content[_startI]):
            no_date_line.append(_content[_startI])
            #logging.info('False:'+_content[_startI])
        else:
            #logging.info('True:'+_content[_startI])
            break
        _startI+=1

    #if 0 == len(no_date_line):
    #    pdb.set_trace()
            
    return no_date_line


def is_exist_date(line):
    date_pattern = re.compile('[\d]{2}-[\d]{2}\s+[\d]{2}:[\d]{2}:[\d]{2}.[0-9]+',re.I)
    rst =re.search(date_pattern , line)
    if None!=rst:
        #logging.info('->True:'+line)
        return True
    else:
        #logging.info('->False:'+line)
        return False


def filter_single_line(_str):
    logging.info('single lint match str:'+_str)
    pattern = re.compile(_str ,re.I)

    src_file_path = cmd_['-f']
    if False == os.path.exists(src_file_path):
        logging.error('file not exist:'+src_file)
        return -1

    src_file = open(src_file_path,'r')
    src_content = src_file.readlines()

    dest_file = open('./rst','w')

    for line in src_content:
        rst =re.search(pattern , line)
        if None!=rst:
            #logging.info('line:'+line)
            dest_file.write(line)
    dest_file.flush()
    dest_file.close()


def filter_multi_line(_str):
    logging.info('multi line match str:'+_str)
    pattern = re.compile(_str ,re.I)

    src_file_path = cmd_['-f']
    if False == os.path.exists(src_file_path):
        logging.error('file not exist:'+src_file)
        return -1

    src_file = open(src_file_path,'r')
    src_content = src_file.readlines()

    line_index = 0;
    for line in src_content:
        rst =re.search(pattern , line)
        if None!=rst:
            write_range(line_index , src_content)
        line_index=line_index+1


def write_range(_cur_index , _content):
    #pdb.set_trace()
    prev_line_index = find_prev_line(0 , _cur_index,_content)
    #pdb.set_trace()
    if 0==len(prev_line_index):
        logging.error('not find prev line')
        return
    else:
        prev_line_index.append(_cur_index)

    next_line_index = find_next_line(_cur_index+1 ,_content)
    #pdb.set_trace()
    if 0==len(next_line_index):
        logging.error('not find next line')
        return
    else:
        prev_line_index = prev_line_index + next_line_index

    #pdb.set_trace()
    dest_file = open('./rst','a')
    for i in prev_line_index:
        dest_file.write(_content[i])

    dest_file.flush()
    dest_file.close()


def find_prev_line(_startI , _endI ,_content):
    date_pattern = re.compile('[\d]{2}-[\d]{2}\s+[\d]{2}:[\d]{2}:[\d]{2}.[0-9]+\s+[0-9]+\s+[0-9]+',re.I)
    i = _startI
    target = _endI

    target_indexs = []

    while i<_endI:
        rst = re.search(date_pattern , _content[i])
        if None!=rst:
            logging.info('aa:'+_content[i])
            if "{" in _content[i]:
                target = i
                break;
        i=i+1
                
    if _endI == target:
        return target_indexs

    while target<_endI:
        target_indexs.append(target)
        target=target+1

    return target_indexs

def find_next_line(_startI ,_content):
    target_indexs = []

    endI = len(_content)
    while _startI<endI:
        target_indexs.append(_startI)
        if "}" == _content[_startI]:
            logging.info(_content[_startI])
            break;
        _startI=_startI+1

    return target_indexs

#=================test code =================================================
if __name__=='__main__':
    logging.info('argv is:'+str(sys.argv))
    if len(sys.argv) <=1:
        logging.error("argv too little")
    else:
        i = 1;
        while i<len(sys.argv) and i+1<len(sys.argv):
            logging.info('i:'+str(i))
            cmd_[sys.argv[i]] = sys.argv[i+1]
            i=i+2

        deal_cmd(cmd_)

